$(function () {
    const body = $('body');

    loadUsersTable()
    loadUserInfo()

    body.on('click', '.btn-change-role', function (event) {
        const data = {}
        const row = event.target.closest('tr')
        data['username'] = row.dataset.username
        const isAdditional = row.dataset.additional === 'true'
        data['additional'] = isAdditional

        const changeRoleParam = {}
        changeRoleParam['path'] = '/api/user'
        changeRoleParam['method'] = 'put'
        changeRoleParam['data'] = data
        loadButtonClick(event, changeRoleParam, () => {
            const btn = event.target.closest('button')
            btn.innerHTML = isAdditional ? '<span class="icon has-text-success"><ion-icon name="lock-open-sharp"></ion-icon></span>'
                : '<span class="icon has-text-danger"><ion-icon name="lock-closed-sharp"></ion-icon></span>'
            row.dataset.additional = isAdditional ? 'false' : 'true'

        })
    });

    body.on('mousedown mouseup', '.btn-show-data', function (event) {
        const btn = event.target.closest('button');
        const targetName = btn.dataset.target;
        const form = btn.closest('div#user-form')
        const type = form.querySelector('input[name="'+targetName+'"]').type;
        form.querySelector('input[name="'+targetName+'"]').type = type === 'password' ? 'text' : 'password';
    });

    function loadUserInfo() {
        $.ajax({
            url: '/api/user',
            method: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            success: function (data) {
                $('#user-info').text(data['firstName'] + ' ' + data['lastName']);
            }
        });
    }

    function loadUsersTable() {
        $('#user-table').load('/user')
    }

})